package cos

import (
	"ginblog/utils/errmsg"
	"time"

	sts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
)

// Options 获取上传文件临时cos密钥参数
type Options struct {
	COSSecretID  string
	COSSecretKEY string
	AppID        string
	Bucket       string
	Region       string
	UserImgPath  string // 规范图片归属userImgPath："/{articleImg}/{UserName}"
}

// GetTempCredential 获取上传文件临时cos密钥，1分钟失效！规范图片归属userImgPath："/{articleImg}/{UserName}"
func GetTempCredential(opts *Options) (credentials *sts.CredentialResult, code int) {
	c := sts.NewClient(
		opts.COSSecretID,
		opts.COSSecretKEY,
		nil,
	)
	opt := &sts.CredentialOptions{
		DurationSeconds: int64(time.Minute.Seconds()),
		Region:          opts.Region,
		Policy: &sts.CredentialPolicy{
			Statement: []sts.CredentialPolicyStatement{
				{
					Action: []string{
						// 具体说明 https://cloud.tencent.com/document/product/436/31923
						"name/cos:PostObject",
						"name/cos:PutObject",
					},
					Effect: "allow",
					Resource: []string{
						//这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
						"qcs::cos:" + opts.Region + ":uid/" + opts.AppID + ":" + opts.Bucket + opts.UserImgPath,
					},
				},
			},
		},
	}
	res, err := c.GetCredential(opt)
	if err != nil {
		panic(err)
	}
	return res, errmsg.SUCCESS
}
